<?php

namespace Trawind\Workflows;

use Trawind\Helpers\UserHelper;
use Trawind\Remotes\Repositories\User\UserRepositoryEloquent;

trait WorkflowQuery
{
    use ServiceConnect;

    protected $query_remote = "&source=remote";
    protected $query_remote_none = "?source=remote";
    protected function workflowTranslation($fromStateId): array
    {
        $query = "?search=from_state_id:{$fromStateId}";
        return $this->request(parent::WORKFLOW_TRANSLATION_PATH, [], $query . $this->query_remote);
    }

    protected function translationButtonClickdRequest($id): array
    {
        $query = "/{$id}?with=workflowTranslationButtonCondition.workflowExecuteButtons&workflow_execute_id={$this->workflowCurrentExecuteState['id']}";
        return $this->request(parent::WORKFLOW_TRANSLATION_PATH, [], $query . $this->query_remote);
    }

    protected function workflowExecuteButtons($id): array
    {
        $query = "?search=workflow_execute_id:{$id}";
        return $this->request(parent::WORKFLOW_EXECUTE_BUTTON_PATH, [], $query . $this->query_remote, 'GET', ['MS-Request-ServiceName' => null]);
    }

    protected function updateExecuteField()
    {
    }
    protected function workflowExecuteFields($id): array
    {
        $query = "?search=workflow_execute_id:{$id}";
        return $this->request(parent::WORKFLOW_EXECUTE_FIELD_PATH, [], $query . $this->query_remote, 'GET');
    }

    protected function workflowExecuteLogs(): array
    {
        //$query = "?search=executeWorkflow.workflow_id:{$this->workflow['id']};executeWorkflow.resource_record_id:{$this->model->id}&with=executeWorkflow.workflow;state;action;actionTypes&searchFields=executeWorkflow.workflow.id:=;executeWorkflow.resource_record_id:=&searchJoin=and";
        $query = "?search=workflow_execute_id:{$this->workflowCurrentExecuteState['id']}&with=executeWorkflow.workflow;state;action;actionTypes&searchJoin=and&pageSize=999";
        return $this->request(parent::WORKFLOW_EXECUTE_LOG_PATH, [], $query . $this->query_remote);
    }

    protected function workflowConditionsRequest($workflowId): array
    {
        $query = "?search=workflow_id:{$workflowId}";
        return $this->request(parent::WORKFLOW_CONDITION_PATH, [], $query . $this->query_remote);
    }

    protected function workflowStateConditionsRequest($workflowStateId): array
    {
        $query = "?search=state_id:{$workflowStateId};resource_id:0,{$this->model->id}&searchJoin=and&searchFields=state_id:=;resource_id:in";
        return $this->request(parent::WORKFLOW_CONDITION_PATH, [], $query . $this->query_remote);
    }

    protected function updateNextStateConditionRequest($director_id): array
    {
        $body = [
            'state_id' => $this->translation['to_state_id'],
            'type_type_id' => 11,
            'compare' => 30,
            'resource_id' => $this->model->id,
            'value' => app(UserRepositoryEloquent::class)->getListBySearch([
                'search' => 'person_type_id:10;person_id:' . $director_id,
                'searchJoin' => 'and',
                'searchFields' => 'person_id:in',
            ])['data'][0]['id'] ?? 0,
        ];
        return $this->request(parent::WORKFLOW_CONDITION_PATH, $body, $this->query_remote_none, 'POST' );
    }
    protected function updateButtonConditionRequest($user_id, $workflowAction): array
    {
        $body = [
            'action_id' => $workflowAction['id'],
            'state_id' => $this->workflowCurrentExecuteState['current_state_id'],
            'type_type_id' => 11,
            'compare' => 30,
            'resource_id' => $this->model->id,
            'value' => $user_id,
        ];
        return $this->request(parent::WORKFLOW_CONDITION_PATH, $body, $this->query_remote_none, 'POST' );
    }
    protected function workflowTranslationConditionsRequest($translation_id): array
    {
        $query = "?search=translation_id:{$translation_id}";
        return $this->request(parent::WORKFLOW_CONDITION_PATH, [], $query . $this->query_remote);
    }

    protected function conditionsRequest($resourceRecordId, $workflowId): array
    {
        $query = "?search=resource_record_id:{$resourceRecordId};workflow_id:{$workflowId}&searchJoin=and&with=workflowState.workflowActions.conditions";
        return $this->request(parent::WORKFLOW_EXECUTE_PATH, [], $query . $this->query_remote);
    }

    protected function workflowCurrentExecuteState($workflowId, $resourceRecordId): array
    {
        $query = "?search=resource_record_id:{$resourceRecordId};workflow_id:{$workflowId}&searchJoin=and&with=workflowState.workflowActions.action;workflowState.workflowActions.actionType";
        return $this->request(parent::WORKFLOW_EXECUTE_PATH, [], $query . $this->query_remote);
    }

    public function checkWorkflow(): array
    {
        $query = "?search=resource:{$this->controllerIdentifier}&trigger_type={$this->triggerType}&event_type={$this->eventType}";
        return $this->request(parent::WORKFLOW_PATH, [], $query . $this->query_remote);
    }

    protected function addFieldsRequest($name, $value, $label, $field_id, $require): array
    {
        $body = [
            'label' => $label,
            'value' => $value,
            'name' => $name,
            'field_id' => $field_id,
            'workflow_execute_id' => $this->workflowCurrentExecuteState['id'],
            'require' => $require,
        ];
        return $this->request(parent::WORKFLOW_EXECUTE_FIELD_PATH, $body, $this->query_remote_none, 'POST');
    }

    protected function updateWorkflowFieldValueRequest($updateWorkflowFieldValueRequestId, $name, $value): array
    {
        $query = "?search=name:{$name};workflow_execute_id:{$updateWorkflowFieldValueRequestId}&searchJoin=and";
        $body = [
            'value' => $value
        ];
        return $this->request(parent::WORKFLOW_EXECUTE_FIELD_PATH . '/updateWorkflowFieldValueRequest', $body, $query . $this->query_remote, 'PUT');
    }

    protected function addButtonActionRequest($id, $label, $name, $confirm_type_id = 0): array
    {
        $body = [
            'button_label' => $label,
            'button_id' => $id,
            'button_name' => $name,
            'confirm_type_id' => $confirm_type_id,
            'workflow_execute_id' => $this->workflowCurrentExecuteState['id']
        ];
        return $this->request(parent::WORKFLOW_EXECUTE_BUTTON_PATH, $body, $this->query_remote_none, 'POST');
    }

    protected function removeButtonRequest(): array
    {
        $query = "?search=workflow_execute_id:{$this->workflowCurrentExecuteState['id']}";
        return $this->request(parent::WORKFLOW_EXECUTE_BUTTON_PATH . '/removeButtonRequest', [], $query . $this->query_remote, 'DELETE');
    }

    protected function removeFieldRequest($name): array
    {
        $query = "?search=name:{$name};workflow_execute_id:{$this->workflowCurrentExecuteState['id']}&searchJoin=and";

        return $this->request(parent::WORKFLOW_EXECUTE_FIELD_PATH . '/removeWorkflowFieldValueRequest', [], $query . $this->query_remote, 'delete');
    }

    protected function translationCurrentExecuteStateRequest($stateId, $id): array
    {
        $body = [
            'current_state_id' => $stateId,
            'current_action_id' => 0,
        ];
        return $this->request(parent::WORKFLOW_EXECUTE_PATH . "/{$id}", $body, $this->query_remote_none, 'PUT');
    }

    protected function startWorkflow($workflow, $model): array
    {
        $body = [
            'workflow_id' => $workflow['id'],
            'resource_record_id' => $model->id
        ];
        $result = $this->request(parent::WORKFLOW_EXECUTE_PATH . '/startWorkflow', $body, '', 'POST');

        $this->writeWorkflowLog(30, 0, 0, 0, $result['data']['id'] ?? 0);
        $this->writeWorkflowLog(10, 0, 0, $result['data']['current_state_id'] ?? 0, $result['data']['id'] ?? 0);
        return $result;
    }

    protected function writeWorkflowLog($executeTypeId = 0, $actionType = 0, $actionId = 0, $stateId = null, $workflowCurrentExecuteStateId = null, $defaultParams = []): array
    {
        $executedAt = $defaultParams['executedAt'] ?? date('Y-m-d H:i:s', time());
        $executerId = $defaultParams['executerId'] ?? UserHelper::userId();
        $workflowCurrentExecuteStateId = $workflowCurrentExecuteStateId ?? $this->workflowCurrentExecuteState['id'] ?? 0;
        $stateId = $stateId ?? $this->workflowCurrentExecuteState['current_state_id'] ?? 0;
        $body = [
            'workflow_execute_id' => $workflowCurrentExecuteStateId,
            'state_id' => $stateId,
            'execute_type_id' => $executeTypeId,
            'action_id' => $actionId,
            'action_type' => $actionType,
            // 'action_type_id' => $actionTypeId,
            'executer_id' => $executerId,
            'executed_at' => $executedAt
        ];
        return $this->request(parent::WORKFLOW_EXECUTE_LOG_PATH, $body, $this->query_remote_none, 'POST');
    }

    protected function updateConfirmValue($value = null): array
    {
        $query = "/{$this->workflowCurrentExecuteState['id']}";
        $body = [
            'confirm_value' => $value
        ];
        return $this->request(parent::WORKFLOW_EXECUTE_PATH . $query, $body, $this->query_remote_none, 'PUT');
    }

    protected function updateCurrentAction($id): array
    {
        $query = "/{$this->workflowCurrentExecuteState['id']}";
        $body = [
            'current_action_id' => $id
        ];
        return $this->request(parent::WORKFLOW_EXECUTE_PATH . $query, $body, $this->query_remote_none, 'PUT');
    }

    protected function clearCurrentExecuteStateConitionsRequest()
    {
        $query = "?search=resource_id:{$this->model->id};state_id:{$this->workflowCurrentExecuteState['current_state_id']}&searchJoin=and";
        return $this->request(parent::WORKFLOW_CONDITION_PATH . '/clearCurrentExecuteStateConitionsRequest', [], $query . $this->query_remote, 'DELETE');
    }
}
